package com.venutech.gongan.api;

import com.baomidou.mybatisplus.plugins.Page;
import com.shihang.misc.date.DateTimeUtil;
import com.venutech.gongan.common.Constants;
import com.venutech.gongan.entity.BarCode;
import com.venutech.gongan.entity.DictData;
import com.venutech.gongan.entity.RzLog;
import com.venutech.gongan.model.ResultFormat;
import com.venutech.gongan.service.AuditLogService;
import com.venutech.gongan.service.BarCodeService;
import com.venutech.gongan.service.DictDataService;
import com.venutech.gongan.service.RzLogService;
import com.venutech.gongan.util.ResultUtil;
import com.venutech.gongan.vo.BarCodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

@RestController
@Api(tags = {"条形码控制层接口"})
public class BarCodeController extends AbstractControllerBase {
    @Resource
    private BarCodeService barCodeService;
    @Resource
    private RzLogService rzLogService;
    @Resource
    private DictDataService dictDataService;
    @Autowired
    ApplicationContext applicationContext;

    @Value("${barcode.save-dir}")
    String barCodeSaveDir;

    @Value("${barcode.path-mapping}")
    String barCodePathMapping;


    Logger logger = LoggerFactory.getLogger(BarCodeController.class);
    @PostMapping("/barcodeServer_List")
    @ResponseBody
    public Map<String, Object> barcodeServer_List(@RequestParam Integer page, @RequestParam Integer limit,
                                         @RequestParam(required = false) String begintime,
                                         @RequestParam(required = false) String endtime,
                                         @RequestParam(required = false) String badw,
                                         @RequestParam(required = false) String bc_sn,
                                          @RequestParam(required = false,defaultValue = "0") Integer type) throws Exception {
        logger.info("SN名称:  "+bc_sn);
        RzLog rzLog = new RzLog();
        Map<String, Object> result = new HashMap<>();
        Page<BarCode> p = barCodeService.getInfo(page,limit,begintime,endtime,badw,bc_sn);
        result.put("code","0");
        result.put("count",p.getTotal());
        result.put("data",p.getRecords());
        if(type==1){
            String message = String.format("条形码=%s", bc_sn);
            String opCondition = String.format("条形码=%s",bc_sn);
            asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.QUERY, opCondition, message);
        }else{
            result.put("msg","查询成功");
        }
        return result;
    }

    @DeleteMapping("/barCodeServerDelete")
    @ResponseBody
    public ResultFormat barCodeServerDelete(@RequestParam Integer bc_id) {
        barCodeService.deleteById(bc_id);
        eventThreadPool.execute(() -> {
            try {
                BarCode barCode = barCodeService.getById(bc_id);
                String message = String.format("删除条形码：　条形码Id：%d, 条形码编码：%s", barCode.getBc_id(), barCode.getBc_bm());
                String opCondition = String.format("bc_id=%d", bc_id);

                asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_DELETE, Constants.DELETE, opCondition, message);

            } catch(Exception ex) {
                logger.warn("BarCodeController.barCodeServerDelete(): 日志记录异常， ex=", ex);
            }
        });
        return ResultUtil.success();
    }

    @PostMapping(value = "/barcodeServerSave")
    @ApiOperation(value = "条形码保存页面")
    @ResponseBody
    public ResultFormat barcodeServerSave(BarCode barCode) throws IOException {
        barCodeService.createBarCodeWithFile(barCode);

        String message = String.format("添加条形码：　条形码Id：%d, 条形码编码：%s", barCode.getBc_id(), barCode.getBc_bm());
        String opCondition = String.format("bc_id=%d", barCode.getBc_id());
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_ADD, Constants.INSERT, opCondition, message);


        return ResultUtil.success();
    }

    //修改跳转 http://localhost:8084/images/events/ereport/cd5f5415b496002323232011000078.png
    @GetMapping("/barcode/options")
    public Map<String, Object> barCodeServerUpdateView() throws IOException {

        List<DictData> listyys = dictDataService.getSelAllyys();
        List<DictData> list = dictDataService.getSelAllXh();
        List<DictData> listsblb = dictDataService.getAllDictName("sblb");

        Map<String, Object> model = new HashMap<>();

        model.put("list",list);
        model.put("listyys",listyys);
        model.put("listsblb", listsblb);

        return model;
    }

    @GetMapping("/barcode/detail/{id}")
    public BarCodeVO barcodeDetail(@PathVariable("id") String id) {
        BarCode barCode = barCodeService.getBarcodeInfo(id);
        BarCodeVO vo = new BarCodeVO();
        BeanUtils.copyProperties(barCode, vo);

        vo.setNewSrc(String.format("%s%s", barCodePathMapping, barCode.getBc_picid()));
        return vo;
    }

    @PostMapping(value = "/barCodeServerUpdate")
    @ResponseBody
    public ResultFormat barCodeServerUpdate(BarCode barCode, Model model){
        barCodeService.updateBarCode(barCode);

        String message = String.format("更新条形码详情：　条形码Id：%d, 条形码编码：%s", barCode.getBc_id(), barCode.getBc_bm());
        String opCondition = String.format("bc_id=%d", barCode.getBc_id());

        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_UPDATE, Constants.UPDATE, opCondition, message);

        return ResultUtil.success("success");
    }

}
